//----------------------new--------------------

import { http } from '../../server/http.server';
import { httpRouter } from '../../server/http.router';
import { _ } from '../../libs/underscore/underscore.modified';
import { location } from '../../server/location';
import { coordinate } from '../../server/coordinate';

let app = getApp();
let interval;
let deIndex = 0;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //景点信息
    spotId:"",              //景点Id                       
    scenic:{},              //景点信息
    poiList: [],            //景点POI列表
    poiDefList: [],         //景点原始POI列表
    //地图参数
    latitude:0,
    longitude:0,
    polyline: [],           //路径
    markers: [],            //标记点
    controls: [],           //控件
    scale:15,               //缩放级别
    markerStatus: true,     //标记点点击状态
    calloutHidden: false,   //标记点气泡显示状态
    
    //讲解
    isInSpot:false,         //是否在景区
    spotInfo:{},            //当前经纬度景区信息
    currentVioce:{},        //当前讲解
    nextVioce:{},
    playIndex: -1,           //
    freeList:[],            //空闲讲解队列
    passiveList:[],         //被动讲解队列
    voiceList:[],           //播放队列
    voiceLength:0,
    historyList: [],        //历史列队
    defaultPlay:false,
    allPlay: false,

    autoPlay:false,



    //todo
    poi:{},
    routerList:[],
    routerStatus:false,
    routerId:"",
    

    demoIndex:0,



    ICONS: {
      location: '/images/location.png',
      actlocation: '/images/location-active.png',
      spot: '/images/spot.png',
      actspot: '/images/spot-active.png',
      point: '/images/point.png'
    },
    
    playTitle:'',
    playPoiId:0,
    playStatus:false,           //讲解播放状态
    newvoiceList:[],
    bublleContent:"",
    bublleStatus:false,

    //加载状态
    freeStatus:false,           //空闲加载状态
    passiveStatus:false,        //被动加载状态
    spotPoiStatus:false,        //景点POI加载状态
    loadStatus:true             //页面加载状态
  },
  
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    this.audioCtx = wx.createAudioContext('audio');
    this.dfCtx = wx.createAudioContext('defaultAudio');

    this.getSystemInfo(options.spotId);
    this.getSpots(options.spotId);
    this.freetime(options.spotId);
    this.position();
   
    
    
  },

  /**
  * 播放
  */

  play:function(){
    let that = this;
    if (this.data.playStatus || this.data.defaultPlay){
      clearInterval(interval);
      this.audioCtx.pause();
      this.dfCtx.pause();
      this.setData({
        playStatus: false,
        defaultPlay:false,
        allPlay:false,
      });
      return;
    }
    this.data.allPlay=true;
    if (this.data.playIndex >=  this.data.voiceList.length){
      this.dfCtx.play();
      this.setData({
        defaultPlay: true
      });
      return;
    }
    if (this.data.isInSpot && (this.data.spotId == this.data.spotInfo.SpotId)) {
      this.data.autoPlay = true;
      interval = setInterval(function () {
        if (that.data.playStatus || that.data.defaultPlay){
          that.getLocation();
        }
      }, 15000);

      

      this.voicePlay();
    } else {
      
      this.data.playIndex = this.data.playIndex < 0 ? 0 : this.data.playIndex;
      this.getCurrentVoice(this.data.playIndex);
      this.setData({
        playStatus:true
      });
      this.audioPlayF();
    }
  },

  voicePlay: function () {
    let that = this;
    this.data.playIndex = this.data.playIndex < 0 ? 0 : this.data.playIndex;
    if (this.data.playIndex < this.data.voiceList.length) {
      this.getCurrentVoice(this.data.playIndex);
      this.dfCtx.pause();
      this.setData({
        playStatus: true,
        defaultPlay: false
      });
      this.getCurrentIndex();
      this.audioPlayF();
    } else {
      this.audioCtx.pause();
      this.dfCtx.play();
      this.setData({
        playStatus: false,
        defaultPlay: true,
        playPoiId: -9
      });
      this.getCurrentIndex();
    }
  },




  //合并数组
  mergeArray: function (array, filters) {

    try{
      if (array.length <= 0 && filters.length <= 0) {
        return array;
      }
      for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < filters.length; j++) {
          if (filters[j] == null || !filters[j].ContentId) {

          }
          if (array[i].ContentId == filters[j].ContentId) {
            array.splice(i, 1);
          }
        }
      }
    }catch(err){
      
    }
   
   
    return array;
  },
  //拆分数组
  chunk: function (list, index) {
    return {
      before: index<0 ? [] : list.slice(0, index+1),
      current: list.slice(index, index + 1),
      after: list.slice(index + 1)
    }
  },

  getCurrentVoice: function (index){
    index = index || 0;
    let current = this.data.voiceList[index];
 
    this.setData({
      currentVioce: current,
      nextVioce: this.data.voiceList[index+1],
      playIndex: index,
      playPoiId: current.PoiId
    });
  },
  /**
   * 下一曲
   */
  next: function () {
    let that = this;
    let index = this.data.playIndex + 1;
    if (index < this.data.voiceList.length) {
      this.getCurrentVoice(index);
      this.getCurrentIndex();
     
      this.dfCtx.pause();
      this.setData({
        playStatus: true,
        defaultPlay: false
      });
      this.audioPlayF();
    } else {
      this.setData({
        bublleContent: "当前已是最后一个",
        bublleStatus: true
      });
      setTimeout(function () {
        that.setData({
          bublleStatus: false
        });
      }, 1000);
    }
  },
  /**
   * 上一曲
   */
  prev: function () {
    let that = this;
    let index = this.data.playIndex - 1;
    if (index >= 0) {
      this.getCurrentVoice(index);
      this.getCurrentIndex();
     
      this.dfCtx.pause();
      this.setData({
        playStatus: true,
        defaultPlay: false
      });
      this.audioPlayF();
    } else {
      this.setData({
        bublleContent: "当前已是第一个",
        bublleStatus: true
      });
      setTimeout(function () {
        that.setData({
          bublleStatus: false
        });
      }, 1000);
    }
  },

  getCurrentIndex: function () {
    let that = this;
    let list = _.map(this.data.markers, function (item) {
    
      if (item.id == that.data.playPoiId) {
        if (item.markertatus >= 0 && item.markertatus < 4) {
          let mkt = item.markertatus+4;
          item.iconPath = that.getMarkerIcon(mkt);
          item.markertatus = mkt;
        }
        if (item.markertatus >= 8 && item.markertatus < 12) {
          let mkt = item.markertatus-4;
          item.iconPath = that.getMarkerIcon(mkt);
          item.markertatus = mkt;
        }
      
      }else{
        if (item.markertatus >= 4 && item.markertatus < 8) {
          let mkt = item.markertatus + 4;
          item.iconPath = that.getMarkerIcon(mkt);
          item.markertatus = mkt;
          
        }
      }
      return item;
    })
    this.setData({
      markers: list,
      poiDefList: list
    });
  },
  audioPlayF:function(){
    let that = this;
    that.audioCtx.play();
    setTimeout(() => {
      that.audioCtx.play();
    }, 1000);
  },
  /**
   * 结束
   */
  voiceEnd: function () {
    this.data.historyList.push(this.data.currentVioce);


    this.data.playIndex +=1;
    if (this.data.isInSpot && (this.data.spotId == this.data.spotInfo.SpotId)) {
      if (this.data.playIndex < this.data.voiceList.length) {
        this.getCurrentVoice(this.data.playIndex);
        this.audioCtx.seek(0);
        this.setData({
          playStatus: true
        });
        this.getCurrentIndex();
        this.audioPlayF();
      } else {
        this.dfCtx.play();
        this.audioCtx.pause();
        this.setData({
          playStatus: false,
          defaultPlay: true,
          playPoiId:0
        });
        this.getCurrentIndex();
      }
    }else{
      if (this.data.playIndex < this.data.voiceList.length) {
        this.getCurrentVoice(this.data.playIndex);
        this.setData({
          playStatus: true
        });
        this.getCurrentIndex();
        this.audioPlayF();
      } else {
        this.audioCtx.pause();
        this.setData({
          playStatus: false
        });
        
      }
    }
    
  },

  /**
   * 是否在景区
   */
  position: function () {
    let that = this;
    console.log("************position22222");
    location.get().subscribe({
      next: loc => {
        console.log("************position++++location");
        let url = httpRouter.position(loc.latitude, loc.longitude);
        //let url = httpRouter.position("39.9818378122","116.3078029413");
        http.get(url).subscribe({
          next: res => {
            let info = res.data.Content;
            info.SpotInfo = info.SpotInfo ? info.SpotInfo : { SpotId:0};
            that.setData({
              isInSpot: info.IsInSpot,
              spotInfo: info.SpotInfo,
              passiveStatus: true
            });
            console.log("spotPoiStatus====1");
            if(info.IsInSpot){
              setInterval(function () {
                that.location(true);
              }, 180000);
            }
            if (that.data.isInSpot && (that.data.spotId == that.data.spotInfo.SpotId)) {
              that.getPassive(loc.latitude, loc.longitude, that.data.spotId);
              //that.getPassive("39.9818378122", "116.3078029413", that.data.spotId)
            } 

            
            
            that.loading();
          },
          error: err => {}
        })
      },
      error: err => {}
    });
  },
  getLocation1: function () {
    let that = this;
    let lc = [[
      "39.9818378122", "116.3078029413"
    ], [
        "39.9815375637","116.3092643263"
    ], [
      "39.9824297071","116.3069821853"
    ], [
        "39.9187292736", "116.3907384536"
    ], [
        "39.9196837585", "116.3890647551"
    ], [
        "39.9175296902", "116.3878215101"
    ]];
    if (!this.data.allPlay) {
      return;
    }
    deIndex += 1;
    location.get().subscribe({
      next: res => {
        //that.getPassive(res.latitude, res.longitude, this.data.spotId);
        if (that.data.demoIndex >= lc.length){
          that.data.demoIndex = lc.length-1;
        }
        that.getPassive(lc[that.data.demoIndex][0], lc[that.data.demoIndex][1], this.data.spotId);
        that.setData({
          demoIndex: that.data.demoIndex
        })
        if (deIndex > 9){
          that.setData({
            demoIndex: that.data.demoIndex+1
          })
        }
      },
      error: err => {}
    });
  },
  getLocation: function (flag) {
    let that = this;
    location.get().subscribe({
      next: res => {
        that.getPassive(res.latitude, res.longitude, this.data.spotId);
      },
      error: err => {}
    });
  },
  /**
   * 景区被动讲解
   */
  getPassive: function (lat, lng, spotId) {
    let that = this;
    let url = httpRouter.passive(lat, lng, spotId);
    http.get(url).subscribe({
      next: res => {
        let passiveList = _.map(res.data.Content.PoiList, item => {
          return item.Contents;
        });

        that.data.passiveList = _.flatten(passiveList);
        that.mergeSpotVoice();
        that.data.passiveStatus = true;

        console.log("spotPoiStatus=====2");
        that.loading();
      },
      error: err => { }
    })
  },
  mergeSpotVoice: function () {
    let list = _.union(this.data.freeList, this.data.passiveList);
    list = _.sortBy(list, item => {
      return -item.ContentRelationLevel;
    });
    let chunk = this.chunk(this.data.voiceList, this.data.playIndex);
    list = this.mergeArray(list, this.data.historyList);
    list = this.mergeArray(list, chunk.before);
    this.data.voiceList = _.union(chunk.before, list);
    this.setData({
      voiceLength: this.data.voiceList.length
    });

    if(this.data.defaultPlay && this.data.voiceList.length > 0){
       this.voicePlay()
    }
  },



  /**
  * 景区空闲讲解
  */
  freetime: function (spotId) {
    let that = this;
    let url = httpRouter.freetimeUrl(spotId);
    http.get(url).subscribe({
      next: res => {
        that.data.freeList = res.data.Content.Contents;
        that.data.freeStatus = true;
        console.log("freeStatus");
        that.mergeSpotVoice();
        that.loading()
      },
      error: err => { }
    })
  },

  /**
   * 获取屏幕信息 设置地图菜单
   */
  getSystemInfo: function (spotId){
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.initControls();
        that.getSpotPoiList(spotId);
      }
    })
  },
  /**
   * 初始化地图控件
   */
  initControls: function (){
    let locationIcon = this.data.ICONS.location;
    let spotIcon = this.data.markerStatus ? this.data.ICONS.actspot : this.data.ICONS.spot;
    this.setData({
      controls: [{
        id: "location",
        iconPath: locationIcon,
        position: {
          left: 10,
          top: app.data.systemInfo.windowHeight - 140,
          width: 50,
          height: 50
        },
        clickable: true
      }, {
        id: "spot",
        iconPath: spotIcon,
        position: {
          left: app.data.systemInfo.windowWidth - 60,
          top: 50,
          width: 50,
          height: 50
        },
        clickable: true
      }]
    })
  },
  /**
   * control 事件绑定
   */
  controltap(e) {
    let controlId = e.controlId;
    switch (controlId){
      case "location" :
        this.location(false);
        break;
      case "spot" :
        if (!this.data.markerStatus){
          this.setData({
            markerStatus: true,
            calloutHidden: false
          });
          this.initControls();
          this.getSpotPoiList(this.data.spotId);
        }else{
          this.setData({
            markers: "",
            markerStatus: false,
            calloutHidden: false
          });
          this.initControls();
        }
        break;
      default:
      
    }
  },
  /**
   * 定位到当前地址
   */
  location:function(flag){
    let that = this;
    location.get().subscribe({
      next: res => {
        let gcj = coordinate.wgs84togcj02(parseFloat(res.longitude), parseFloat(res.latitude));
        let marker = {
          iconPath: that.data.ICONS.point,
          markertatus: 99,
          id: "location",
          latitude: gcj[1],
          longitude: gcj[0],
          width: 34,
          height: 34
        }
        let markerList = _.filter(that.data.markers, function(item){
          return item.id != "location";
        }); 
        markerList.push(marker);
       
        if (flag){
          this.setData({
            markers: markerList
          });
        }else{
          this.setData({
            latitude: gcj[1],
            longitude: gcj[0],
            markers: markerList
          });
        }
       
      },
      error: err => {}
    });
  },
  
 

  
  /**
   * 获取景点详情
   * 
   * 
   * 
   */
  getSpots: function (spotId) {
    let that = this;
    http.get(httpRouter.spot(spotId)).subscribe({
      next: res => {
        that.setData({
          spotId: spotId,
          scenic:res.data.Content
        });
      },
      error: err => {}
    })
  },
  /**
   * 获取景区poi列表
   */
  getSpotPoiList: function (spotId){
    let that = this;
    http.get(httpRouter.spotPoiList(spotId)).subscribe({
      next: res => {
        that.initMarkers(res.data.Content.Pois);
        that.getMapLoaction(res.data.Content.Pois);
        that.setData({
          poiList: res.data.Content.Pois,
          poiDefList: res.data.Content.Pois,
          spotPoiStatus: true
        });
        console.log("spotPoiStatus");
        that.location(true);
        that.loading();
      },
      error: err => {}
    })
  },
  
  /**
   * 地图显示景点poi
   */
  initMarkers: function (poiList){
    let that = this;
    let markerList = _.map(poiList, function (item) { 
      return {
        iconPath: that.getMarkerIcon(item.IsHot),
        markertatus: item.IsHot,
        id: item.PoiId,
        latitude: item.Lat,
        longitude: item.Lng,
        width: item.IsHot == 4 ? 50 : 40,
        height: item.IsHot == 4 ? 50 : 40
      }
    });
    this.setData({
      markers: markerList
    });
  },
  /**
   * 地图marker图标
   */
  getMarkerIcon: function (status){
    let iconUrl;
    switch (status) {
      case 0:
        iconUrl = '/images/poi.png';
        break;
      case 1:
        iconUrl = '/images/poihot.png';
        break;
      case 2:
        iconUrl = '/images/poi-big.png';
        break;
      case 3:
        iconUrl = '/images/poihot-big.png';
        break;


      case 4:
        iconUrl = '/images/current.png';
        break;
      case 5:
        iconUrl = '/images/currenthot.png';
        break;
      case 6:
        iconUrl = '/images/current-big.png';
        break;
      case 7:
        iconUrl = '/images/currenthot-big.png';
        break;


      case 8:
        iconUrl = '/images/finish.png';
        break;
      case 9:
        iconUrl = '/images/finishhot.png';
        break;
      case 10:
        iconUrl = '/images/finish-big.png';
        break;
      case 11:
        iconUrl = '/images/finishhot-big.png';
        break;
      default:
        iconUrl = '/images/poi.png';
    }
    return iconUrl;
  },
  /**
   * 获取地图中心点
   */
  getMapLoaction: function (poiList){
    let length = poiList.length;
    let latList = _.sortBy(poiList,function(item){
      return item.Lat;
    });
    let lngList = _.sortBy(poiList, function (item) {
      return item.Lng;
    });
    let lat = (latList[0].Lat + latList[length - 1].Lat)/2;
    let lng = (lngList[0].Lng + lngList[length - 1].Lng)/2;
    let latVal = latList[length - 1].Lat - latList[0].Lat;
    let lngVal = lngList[length - 1].Lng - lngList[0].Lng;
    let scale = this.data.scale;
    if (latVal > 0.03 || lngVal > 0.03){
      scale = 12
    }
    this.setData({
      scale: scale,
      latitude: lat,
      longitude: lng,
    });
  },
  

  
  getMarkerId:function(id){
    let status;
    switch (id) {
      case 0:
        status = 2;
        break;
      case 1:
        status = 3;
        break;
      case 2:
        status = 0;
        break;
      case 3:
        status = 1;
        break;


      case 4:
        status = 6;
        break;
      case 5:
        status = 7;
        break;
      case 6:
        status = 4;
        break;
      case 7:
        status = 5;
        break;


      case 8:
        status = 10;
        break;
      case 9:
        status = 11;
        break;
      case 10:
        status = 8;
        break;
      case 11:
        status = 9;
        break;
      default:
        iconUrl = 0;
    }
    return status;
  },
  /**
   * 标记点点击事件
   */
  markerEvent:function(e){
    let that = this;
    let poiId = e.markerId;
    if (poiId == "location") {
      return item;
    }
    let newMarkers = _.map(this.data.markers, function (item) {
      let imt = item.markertatus;
      

      if (item.id == poiId) {
        
        if(imt != 2 && imt != 3 && imt != 6 && imt != 7 && imt != 10 && imt != 11){
          let markertatus = that.getMarkerId(imt);
          item.iconPath = that.getMarkerIcon(markertatus);
          item.markertatus = markertatus;
        }
        return item;
      }

      if(imt == 2 || imt == 3 || imt == 6 || imt == 7 || imt == 10 || imt == 11){
        let markertatus = that.getMarkerId(imt);
        item.iconPath = that.getMarkerIcon(markertatus);
        item.markertatus = markertatus;
      }


      return item;
    });


    let poi = _.find(this.data.poiList, function (item) {
      if (item.PoiId == poiId) {
        return item;
      }
    });
    this.setData({
      markers: newMarkers,
      poi: poi,
      calloutHidden: true
    });
    //let poiDefList = this.data.poiDefList;
    //this.getPoi(e.markerId,4);
  },

  /**
   * 获取Poi信息
   */
  getPoi:function(poiId,status){
    let poinewList = _.map(this.data.poiList, function (item) {
      if (item.PoiId == poiId) {
        item.IsHot = status;
        return item;
      }
      return item;
    });
    this.initMarkers(poinewList);
    let poi = _.find(this.data.poiList, function (item) { 
      if (item.PoiId == poiId ){
        return item;
      }
    });
    this.setData({
      poi: poi
    });
  },
  /**
   * 地图点击事件
   */
  mapEvent:function(){
    this.reduction();
  },
  reduction:function(){
    let that = this;

    let newMarkers = _.map(this.data.markers, function (item) {
      let imt = item.markertatus;
      if(imt == 2 || imt == 3 || imt == 6 || imt == 7 || imt == 10 || imt == 11){
          let markertatus = that.getMarkerId(item.markertatus);
          item.iconPath = that.getMarkerIcon(markertatus);
          item.markertatus = markertatus;
      }
      return item;
    });

    this.setData({
      markers: newMarkers,
      calloutHidden: false
    });
  },
  /**
   * 获取路径
   */
  getRouter: function () {
    let that = this;
    if (this.data.routerStatus){
      this.setData({
        routerStatus: false
      });
      return;
    }

    if (this.data.routerList.length > 0){
      this.setData({
        routerStatus: true
      });
      return;
    }
    http.get(httpRouter.spotRoutList(this.data.spotId)).subscribe({
      next: res => {
        that.setData({
          routerStatus: true,
          routerList: JSON.parse(res.data.Content.RouteDataJson)
        });
      },
      error: err => {}
    })    
  },
  /**
   * 地图展示路劲
   */
  planRoute:function(e){
    let id = e.currentTarget.dataset.id;
    let poilist = [];
    if (this.data.routerId != id){
      let router = _.find(this.data.routerList, function (item) {
        if (item.Id == id) {
          return item;
        }
      });
      poilist = _.map(router.Points, function (item) {
        let gcj = coordinate.wgs84togcj02(parseFloat(item.X), parseFloat(item.Y));
        return {
          longitude: gcj[0],
          latitude: gcj[1]
        }
      });
    }else{
      id = "";
    }
   
    let polyline = {
      points: poilist,
      color: '#1d604c',
      width: 2,
      dottedLine: true
    }
    this.setData({
      routerId: id,
      routerStatus:false,
      polyline: [polyline]
    });
  },
  /**
   * 查看详细信息
   */
  goDetails: function(e){
    let id = e.currentTarget.dataset.id;
    this.audioCtx.pause();
    this.setData({
      playStatus: false
    });
    wx.navigateTo({
      url: '../poi-details/poi-details?poiId='+id
    })
  },
  onHide1: function () {
    clearInterval(interval);
    this.audioCtx.pause();
    this.dfCtx.pause();
    this.setData({
      playStatus: false,
      defaultPlay: false,
      allPlay: false,
    });
  },
  /**
   * 加载事件
   */
  loading: function () {
    console.log("---------------loading");
    if (this.data.freeStatus && this.data.passiveStatus && this.data.spotPoiStatus) {
      console.log("+++++++++++++++loading");
      this.setData({
        loadStatus: false
      });
    }
  },
  /**
   * 分享
   */
  onShareAppMessage: function (res) {
    return {
      title: 'Ai导游',
      path: '/pages/index/index',
      success: function (res) { },
      fail: function (res) { }
    }
  }

})